<?php

function getItemsInvolvedInTrades($teamId) {
	$sql = "select case itemType when 'PICK' then CONCAT('#', itemIdentifier) else itemIdentifier end as itentifier from trade t inner join tradeitem ti on ti.tradeId = t.id";
	$sql .= " where tradeState = '" . TradeState::Proposed . "' and (partyOneId = $teamId or partyTwoId = $teamId);";
	$result = mysql_query($sql);
	
	$returnResult = "";
	$count = 0;
	while($row = mysql_fetch_array($result)) {
		if ($count > 0) {
			$returnResult .= ",";
		}
		$returnResult .= "'" . $row['itentifier'] . "'";
		$count++;
	}
	
	
	return $returnResult;	
}

function createCounterTrade($parentTradeId, $leagueId) {
        $parentTrade = getTrade($parentTradeId);
	$sql = "INSERT INTO trade (partyOneId, partyTwoId, parentTradeId, tradeState, leagueId, proposeDateTime)";
	$sql .= " values ($parentTrade->partyTwoId, $parentTrade->partyOneId, $parentTradeId, '" . TradeState::Proposed . "', $leagueId, now());";
	mysql_query($sql);
	$id = mysql_insert_id();
	
	return $id;
}

function createTrade($partyOneId, $partyTwoId, $leagueId) {
	$sql = "INSERT INTO trade (partyOneId, partyTwoId, tradeState, leagueId, proposeDateTime, beenDisplayed) values ($partyOneId, $partyTwoId, '" . TradeState::Proposed . "', $leagueId, now(), 'NONE');";
	mysql_query($sql);
	$id = mysql_insert_id();
	
	return $id;
}

function updateTradeToCounter($tradeId) {
	$sql = "UPDATE trade set tradeState = 'COUNTERED' where id = $tradeId;";
	mysql_query($sql);
}

function createTradeItem($tradeId, $itemIdentifier, $itemType, $receiver) {
	$sql = "INSERT INTO tradeitem (tradeId, itemIdentifier, itemType, receiver) values ($tradeId, $itemIdentifier, '$itemType', '$receiver');";
	mysql_query($sql);

}

function getTradesByLeague($leagueId, $page, $maxPerPage) {
	$sql = "select t.id, t1.id as partyOneId, t1.coachName as partyOne, t2.id as partyTwoId, t2.coachName as partyTwo, tradeState, proposeDateTime, responseDateTime from trade t";
	$sql .= " inner join team t1 on t.partyOneId = t1.id inner join team t2 on t.partyTwoId = t2.id where t.leagueId = $leagueId";
	$sql .= " and tradeState in ('" . TradeState::Confirmed . "', '" . TradeState::ConfirmedAndInformed . "') order by id desc";
	
	return getTrades($sql, $page, $maxPerPage);
}

function getCountTradesByLeague($leagueId) {
	$sql = "select count(*) as count from trade where leagueId = $leagueId and tradeState in ('" . TradeState::Confirmed . "', '" . TradeState::ConfirmedAndInformed . "') order by id desc";
	$result = mysql_query($sql);
	$row = mysql_fetch_array($result);
	$count = $row['count'];

	
	return $count;
}

function getTrades($sql, $page, $maxPerPage) {
	
	$tradeResult = mysql_query($sql);
	
	$array = array();
	$count = 1;
	while($row = mysql_fetch_array($tradeResult)) {
		if (($count <= $page*$maxPerPage && ($count > $page*$maxPerPage - $maxPerPage)) || $page == -1) {
			$trade = new Trade();
			$tradeId = $row['id'];
			$trade->id = $tradeId; 
			$trade->partyOne = $row['partyOne'];
			$trade->partyTwo = $row['partyTwo'];
			$trade->partyOneId = $row['partyOneId'];
			$trade->partyTwoId = $row['partyTwoId'];
			$trade->state = $row['tradeState'];
			$trade->proposeDateTime = $row['proposeDateTime'];
			$trade->responseDateTime = $row['responseDateTime'];
			$tradeItemSql = getTradeItemsSQL($tradeId);
			$tradeItemResult = mysql_query($tradeItemSql);
			while($tradeItemRow = mysql_fetch_array($tradeItemResult)) {
				if ($tradeItemRow['itemType'] == TradeItemType::Player) {
					$player = new Player();
					$player->id = $tradeItemRow['playerId'];
					$player->playerFirstName = $tradeItemRow['firstName'];
					$player->playerSurname = $tradeItemRow['surname']; 
					$player->playerType = $tradeItemRow['playerType'];
					$player->team = $tradeItemRow['team'];
					$tradeItem = new TradeItem();
					$tradeItem->player = $player;
					$tradeItem->itemType = TradeItemType::Player;
					if ($tradeItemRow['receiver'] == PartyType::PartyOne) {
						$trade->partyOneReceives[] = $tradeItem;			
					}
					else {
						$trade->partyTwoReceives[] = $tradeItem;
					}
				}
				else {
					$tradeItem = new TradeItem();
					$tradeItem->pickNumber = $tradeItemRow['itemIdentifier'];
					$tradeItem->itemType = TradeItemType::Pick;
					if ($tradeItemRow['receiver'] == PartyType::PartyOne) {
						$trade->partyOneReceives[] = $tradeItem;			
					}
					else {
						$trade->partyTwoReceives[] = $tradeItem;
					}
				}	
			}
		
			$array[] = $trade;
		}
		$count++;		
	}
	
	
	return $array;
}

function getTradeItemsSQL($tradeId) {
	return "select p.id as playerId, itemIdentifier, itemType, p.firstName, p.surname, p.team, p.playerType, receiver from tradeitem ti left join player p on ti.itemIdentifier = p.id and itemType = 'PLAYER'"
	. " where tradeId = $tradeId";
} 

function getTradesByTeam($teamId, $page, $maxPerPage) {
	$sql = "select t.id, t1.id as partyOneId, t1.coachName as partyOne, t2.id as partyTwoId, t2.coachName as partyTwo, tradeState, proposeDateTime, responseDateTime from trade t";
	$sql .= " inner join team t1 on t.partyOneId = t1.id inner join team t2 on t.partyTwoId = t2.id where t.partyOneId = $teamId or t.partyTwoId = $teamId order by id desc";
	
	return getTrades($sql, $page, $maxPerPage);
}

function getCountTradesByTeam($teamId) {
	$sql = "select count(*) as count from trade where partyOneId = $teamId or partyTwoId = $teamId order by id desc";
	$result = mysql_query($sql);
	$row = mysql_fetch_array($result);
	$count = $row['count'];

	
	return $count;
}

function getTrade($tradeId) {
	$sql = "select t.id, t1.id as partyOneId, t1.coachName as partyOne, t2.id as partyTwoId, t2.coachName as partyTwo, tradeState, proposeDateTime, responseDateTime from trade t";
	$sql .= " inner join team t1 on t.partyOneId = t1.id inner join team t2 on t.partyTwoId = t2.id where t.id = $tradeId";
	
	$trades = getTrades($sql, -1, -1);

        return $trades[0];
}

function haveProposedTrades($team) {
	$sql = "select count(*) as numberProposedTrades from trade where partyTwoId = $team->id and tradeState = '" . TradeState::Proposed . "';";
	
	$result = mysql_query($sql);
	
	$row = mysql_fetch_array($result);
	$numberOfPRoposedTrades = $row['numberProposedTrades'];
	
	
	if ($numberOfPRoposedTrades > 0) {
		return true;
	}
	
	return false;
}

function haveConfirmedTrades($team, $forAdmin) {
	$sql = "select count(*) as numberConfirmedTrades from trade where partyOneId = $team->id and (tradeState = '" . TradeState::Confirmed . "' || tradeState = '" . TradeState::ConfirmedAndInformed . "')";
	$sql .= " and beenDisplayed = 'NONE';";
	
	$result = mysql_query($sql);
	
	$row = mysql_fetch_array($result);
	$numberOfConfirmedTrades = $row['numberConfirmedTrades'];
	
	if (!$forAdmin) {
		$sql = "update trade set beenDisplayed = 'SEEN' where partyOneId = $team->id and (tradeState = '" . TradeState::Confirmed . "' || tradeState = '" . TradeState::ConfirmedAndInformed . "')";
		mysql_query($sql);
	}
	
	
	if ($numberOfConfirmedTrades > 0) {
		return true;
	}
	
	return false;
}

function haveRejectedTrades($team, $forAdmin) {
	$sql = "select count(*) as numberRejectedTrades from trade where partyOneId = $team->id and tradeState = '" . TradeState::Rejected . "' and beenDisplayed = 'NONE';";
	
	$result = mysql_query($sql);
	
	$row = mysql_fetch_array($result);
	$numberOfRejectedTrades = $row['numberRejectedTrades'];
	
	if (!$forAdmin) {
		$sql = "update trade set beenDisplayed = 'SEEN' where partyOneId = $team->id and tradeState = '" . TradeState::Rejected . "'";
		mysql_query($sql);
	}
	
	
	if ($numberOfRejectedTrades > 0) {
		return true;
	}
	
	return false;
}

function haveInvalidTrades($team, $forAdmin) {
	$sql = "select count(*) as numberInvalidTrades from trade where ((partyTwoId = $team->id and beenDisplayed not in ('BOTH', 'PARTY_TWO')) or (partyOneId = $team->id and beenDisplayed not in ('BOTH', 'PARTY_ONE')))";
	$sql = " and tradeState = '" . TradeState::Invalid . "';";
	
	$result = mysql_query($sql);
	
	$row = mysql_fetch_array($result);
	$numberOfInvalidTrades = $row['numberInvalidTrades'];
	
	if (!$forAdmin) {
		$sql = "update trade set beenDisplayed = 'PARTY_ONE' where partyOneId = $team->id and beenDisplayed = 'NONE' and tradeState = '" . TradeState::Invalid . "'";
		mysql_query($sql);
	}
	
	$sql = "update trade set beenDisplayed = 'PARTY_TWO' where partyTwoId = $team->id and beenDisplayed = 'NONE' and tradeState = '" . TradeState::Invalid . "'";
	mysql_query($sql);
	
	$sql = "update trade set beenDisplayed = 'BOTH' where ((partyTwoId = $team->id and beenDisplayed = 'PARTY_ONE') or (partyOneId = $team->id and beenDisplayed = 'PARTY_TWO')) and tradeState = '" . TradeState::Invalid . "'";
	mysql_query($sql);
	
	
	if ($numberOfInvalidTrades > 0) {
		return true;
	}
	
	return false;
}

function confirmTrade($tradeId) {
	$tradeSQL = "select * from trade where id = $tradeId";
	$tradeResult = mysql_query($tradeSQL);
	$tradeRow = mysql_fetch_array($tradeResult);
	$partyOneId = $tradeRow['partyOneId']; 
	$partyTwoId = $tradeRow['partyTwoId'];
	
	$sql = getTradeItemsSQL($tradeId);
	$tradeItemResult = mysql_query($sql);
	while($tradeItemRow = mysql_fetch_array($tradeItemResult)) {
		$receiver = null;
		$giver = null;
		if ($tradeItemRow['receiver'] == PartyType::PartyOne) {
			$receiver = $partyOneId;
			$giver = $partyTwoId;
		}
		else {
			$receiver = $partyTwoId;
			$giver = $partyOneId;
		}
		if ($tradeItemRow['itemType'] == TradeItemType::Player) {
			$playerId = $tradeItemRow['playerId'];
			$teamPlayerSQL = "INSERT into teamplayer (playerId, teamId, playerPosition) values (" . $playerId . "," . $receiver . ", 'RES');";
			mysql_query($teamPlayerSQL);
			$updateTeamPlayerSQL = "UPDATE teamplayer set traded = true where playerId = $playerId and teamId = $giver";
			mysql_query($updateTeamPlayerSQL);
		}
		else {
			$draftSQL = "UPDATE playerdraft set teamId = $receiver where picknumber = " . $tradeItemRow['itemIdentifier'];
			mysql_query($draftSQL);
		}
	}
	
	$tradeSQL = "UPDATE trade set tradeState = '" . TradeState::Confirmed . "', responseDateTime = now() where id = $tradeId";
	mysql_query($tradeSQL);

    $sql = "SELECT leagueId from team where id = $partyOneId;";
	$teamResult = mysql_query($sql);
	$teamRow = mysql_fetch_array($teamResult);
	$leagueId = $teamRow['leagueId'];

    validateProposedTrades($leagueId);
}

function rejectTrade($tradeId) {
	$tradeSQL = "UPDATE trade set tradeState = '" . TradeState::Rejected . "', responseDateTime = now() where id = $tradeId";
	mysql_query($tradeSQL);
	
}

function getMadeTrades($leagueId) {
	$sql = "select t.id, t1.id as partyOneId, t1.coachName as partyOne, t2.id as partyTwoId, t2.coachName as partyTwo, tradeState, proposeDateTime, responseDateTime from trade t";
	$sql .= " inner join team t1 on t.partyOneId = t1.id inner join team t2 on t.partyTwoId = t2.id where t.leagueId = $leagueId and tradeState = '" . TradeState::Confirmed . "' order by id desc";

	return getTrades($sql, -1, -1);
}

function getProposedTrades($leagueId) {
	$sql = "select t.id, t1.id as partyOneId, t1.coachName as partyOne, t2.id as partyTwoId, t2.coachName as partyTwo, tradeState, proposeDateTime, responseDateTime from trade t";
	$sql .= " inner join team t1 on t.partyOneId = t1.id inner join team t2 on t.partyTwoId = t2.id where t.leagueId = $leagueId and tradeState = '" . TradeState::Proposed . "'";

	return getTrades($sql, -1, -1);
}

function invalidateTrade($tradeId) {
	$sql = "UPDATE trade set tradeState = 'INVALID' where id = $tradeId;";
	mysql_query($sql);
	
}

function updateTradeToInformed($leagueId) {
	$sql = "UPDATE trade set tradeState = 'CONFIRMED_INFORMED' where tradeState = 'CONFIRMED' and leagueId = $leagueId;";
	mysql_query($sql);
}
?>
